from django.shortcuts import render,redirect
from django.views.decorators.csrf import csrf_exempt

# 注意了 要使用.来引入包 否则会一直报错
from product.models import Product, ProductForm
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

'''
    main首页 
    首先处理是否登录 
    从redis中获取token
'''

# 这儿没使用了 应该是user主页面了
@csrf_exempt
def product_list(request):
    is_admin = False
    # if redis_util.isAdminLogin(request):
    #     is_admin = True
    product_list = Product.objects.all()

    # 处理自定义值
    try:
        # 获取用户选择的每页显示数量，默认为 10
        per_page = int(request.GET.get('per_page', 10))
        per_page = int(per_page)  # 将 per_page 转换为整数
        if per_page <= 0:  # 如果输入的值小于等于0，设置为默认值10
            per_page = 10
    except (ValueError, TypeError):  # 如果 per_page 不是数字，设置为默认值10
        per_page = 10

    # 分页
    paginator = Paginator(product_list, per_page)
    page_number = request.GET.get('page')
    try:
        page_obj = paginator.get_page(page_number)  # 获取当前页
    except PageNotAnInteger:  # 如果 page 不是整数，跳转到第一页
        page_obj = paginator.get_page(1)
    except EmptyPage:  # 如果 page 超出范围，跳转到最后一页
        page_obj = paginator.get_page(paginator.num_pages)

    # 允许的每页显示数量列表
    allowed_per_page = [10, 20, 50, 100, 200]

    return render(request, 'product_list.html', {
        'product_list': page_obj,
        'per_page': per_page,  # 将每页显示数量传递给模板
        'allowed_per_page': allowed_per_page,
        'is_admin': is_admin,
    })
@csrf_exempt
def product_add(request):
    if request.method == "POST":
        print(request.POST.get('name'))
        form = ProductForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('product_list')
    else:
        form = ProductForm()
    return render(request, 'product_add.html', {'form': form})

@csrf_exempt
def product_update(request, pk):
    product = Product.objects.get(id=pk)
    if request.method == "POST":
        # 第二参数很重要 更新现有实例 如果不写会一直新增
        form = ProductForm(request.POST,instance=product)
        if form.is_valid():
            form.save()
            return redirect('product_list')
    else:
        form = ProductForm()
    return render(request, 'product_update.html', {'form': form,"product":product})
@csrf_exempt
def product_delete(request, pk):
    product = Product.objects.get(id=pk)
    if request.method == "POST":
        product.delete()
        return redirect('product_list')
    return render(request, 'product_delete.html', {'product': product})